package com.linewell.encryption.utils.sm2;


import com.linewell.encryption.utils.Base64Utils;
import com.linewell.encryption.utils.ByteUtils;
import com.linewell.encryption.utils.sm2.vo.SM2KeyVO;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.bouncycastle.math.ec.ECPoint;

import java.math.BigInteger;

/**
 * 生成随机秘钥对
 *
 * @author wucan
 * @date 2019-03-14
 */
public class SM2CreateKeyUtils {


    /**
     * 生成随机秘钥对
     *
     * @return 秘钥对对象
     */
    public static SM2KeyVO generateKeyPair() {
        SM2 sm2 = SM2.Instance();
        AsymmetricCipherKeyPair key;
        while (true) {
            key = sm2.ecc_key_pair_generator.generateKeyPair();
            if (((ECPrivateKeyParameters) key.getPrivate()).getD().toByteArray().length == 32) {
                break;
            }
        }
        ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) key.getPrivate();
        ECPublicKeyParameters ecpub = (ECPublicKeyParameters) key.getPublic();
        BigInteger privateKey = ecpriv.getD();
        ECPoint publicKey = ecpub.getQ();
        SM2KeyVO sm2KeyVO = new SM2KeyVO();
        sm2KeyVO.setPublicKey(publicKey);
        sm2KeyVO.setPrivateKey(privateKey);
        System.out.println("公钥: " + Base64Utils.byteToBase64(publicKey.getEncoded()));
        System.out.println("私钥: " + Base64Utils.byteToBase64(privateKey.toByteArray()));
        return sm2KeyVO;
    }


    public static void main(String[] args) throws Exception {

        SM2KeyVO sm2KeyVO = generateKeyPair();
        System.out.println(ByteUtils.byteToHex(sm2KeyVO.getPublicKey().getEncoded()));
        System.out.println(ByteUtils.byteToHex(sm2KeyVO.getPrivateKey().toByteArray()));

    }
}